<template>
  <div>
    <Card>
      <p slot="title">
        权限管理
      </p>
      <div slot="extra">
        <Button class="icon-btn" type="success" @click="alertAdd">
          <span class="ml4">添加</span></Button>
      </div>
      <Table ref="tables" :data="tableData" :columns="columns" border disabled-hover/>
      <div class="page-warp">
        <Page
            :current="page.current"
            :page-size="page.size"
            :total="page.total"
            show-total
            @on-change="pageChange"></Page>
      </div>
    </Card>
    <Modal v-model="modalSetting.show" width="668" :styles="{top: '20%'}" @on-visible-change="doCancel" :mask-closable="false">
      <p slot="header" style="color:#2d8cf0;">
        <Icon type="md-information-circle"></Icon>
        <span>{{formItem.id ? '编辑' : '新增'}}权限组</span>
      </p>
      <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="80">
        <FormItem label="组名称" prop="name">
          <Input v-model="formItem.name" placeholder="请输入权限组名称"></Input>
        </FormItem>
        <FormItem label="组描述" prop="description">
          <Input type="textarea" v-model="formItem.description" placeholder="请输入权限组描述"></Input>
        </FormItem>
        <FormItem label="组授权" prop="rules">
          <div class="rule-list">
            <Tree ref="formTree" :data="ruleList" show-checkbox multiple></Tree>
          </div>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel" style="margin-right: 8px">取消</Button>
        <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>
    <Modal v-model="memberSetting.show" width="588" :styles="{top: '20%'}" :mask-closable="false">
      <p slot="header" style="color:#2d8cf0;">
        <Icon type="md-information-circle"></Icon>
        <span>组成员列表</span>
      </p>
      <div>
        <Table :columns="memberColumns" :data="memberData" border disabled-hover></Table>
      </div>
      <div class="margin-top-15" style="text-align: center">
        <Page :total="memberShow.listCount" :current="memberShow.currentPage"
              :page-size="memberShow.pageSize" @on-change="changeMemberPage"
              show-total></Page>
      </div>
      <p slot="footer"></p>
    </Modal>
  </div>
</template>

<script>
import Icons from '_c/icons'
import { getGroups, addGroup, editGroup, delGroup, getRules, delUserFormGroup, getGroupUsers } from '@/api/system'
export default {
  name: 'auth',
  components: {
    Icons
  },
  data () {
    return {
      ruleList: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      memberShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0,
        gid: 0
      },
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      columns: [
        { title: '序号', key: 'id', width: 65, align: 'center' },
        { title: '权限组', align: 'center', key: 'name', width: 100 },
        { title: '描述', align: 'center', key: 'description' },
        {
          title: '成员授权',
          align: 'center',
          key: 'member',
          width: 116,
          render: (h, params) => {
            let _this = this
            let currentRowData = _this.tableData[params.index]
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  margin: '0 5px'
                },
                on: {
                  'click': () => {
                    _this.memberSetting.show = true
                    _this.memberShow.gid = currentRowData.id
                    _this.getMemberList()
                  }
                }
              }, '组成员')
            ])
          }
        },
        {
          title: '状态',
          key: 'status',
          width: 100,
          align: 'center',
          render: (h, params) => {
            let _this = this
            let { id, status } = params.row
            return h('i-switch', {
              attrs: {
                size: 'large'
              },
              props: {
                'true-value': 1,
                'false-value': 0,
                value: status
              },
              on: {
                'on-change': (status) => {
                  editGroup(id, { status }).then(res => {
                    if (res.code === 1) {
                      _this.$Message.success(res.msg)
                    } else {
                      _this.$Message.error(res.msg)
                    }
                  })
                }
              }
            }, [
              h('span', {
                slot: 'open'
              }, '启用'),
              h('span', {
                slot: 'close'
              }, '禁用')
            ])
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          align: 'center',
          render: (h, params) => {
            let _this = this
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click () {
                    _this.formItem.id = params.row.id
                    _this.formItem.name = params.row.name
                    _this.formItem.description = params.row.description
                    getRules({ group_id: params.row.id }).then(res => {
                      if (res.code === 1) {
                        _this.ruleList = res.data
                      } else {
                        _this.$Message.error(res.msg)
                      }
                    })
                    _this.modalSetting.show = true
                    _this.modalSetting.index = params.index
                  }
                }
              }, '编辑'),
              h('Poptip', {
                style: {
                  'textAlign': 'left'
                },
                props: {
                  confirm: true,
                  title: '确定删除？'
                },
                on: {
                  'on-ok': () => {
                    let { id } = params.row
                    delGroup(id).then(res => {
                      if (res.code === 1) {
                        this.$Message.success(res.msg)
                        this.getList()
                      } else {
                        this.$Message.error(res.msg)
                      }
                    })
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  }
                }, '删除')
              ])
            ])
          }
        }
      ],
      tableData: [],
      memberColumns: [
        {
          title: '序号',
          key: 'id',
          width: 65,
          align: 'center'
        },
        {
          title: '名称',
          align: 'center',
          key: 'name',
          width: 90
        },
        {
          title: '用户账号',
          align: 'center',
          key: 'username'
        },
        {
          title: '状态',
          key: 'status',
          align: 'center',
          render: (h, params) => {
            let { status } = params.row
            return h('div', [
              h('Button', {
                props: {
                  type: status === 1 ? 'primary' : 'error',
                  size: 'small'
                }
              }, status === 1 ? '启用' : '禁用')
            ])
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 175,
          align: 'center',
          render: (h, params) => {
            let _this = this
            return h('div', [
              h('Poptip', {
                style: {
                  'textAlign': 'left'
                },
                props: {
                  confirm: true,
                  title: '确定删除？'
                },
                on: {
                  'on-ok': () => {
                    let { id } = params.row
                    let gid = _this.memberShow.gid
                    delUserFormGroup({ uid: id, gid: gid }).then(function (res) {
                      if (res.code === 1) {
                        _this.memberData.splice(params.index, 1)
                        _this.$Message.success(res.msg)
                      } else {
                        _this.$Message.error(res.msg)
                      }
                    })
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  }
                }, '删除')
              ])
            ])
          }
        }

      ],
      memberData: [],
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      memberSetting: {
        show: false,
        loading: false,
        index: 0
      },
      formItem: {
        name: '',
        description: '',
        rules: [],
        id: 0
      },
      ruleValidate: {
        name: [
          { required: true, message: '组名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    pageChange (page) {
      this.page.current = page
      this.getList()
    },
    getList () {
      let { current: page, size } = this.page
      getGroups({ page, size }).then(res => {
        if (res.code === 1) {
          this.tableData = res.data.list
          this.page.total = res.data.count
        }
      })
    },
    getMemberList () {
      let _this = this
      let param = {
        page: _this.memberShow.currentPage,
        size: _this.memberShow.pageSize
      }
      getGroupUsers(_this.memberShow.gid, param).then(res => {
        if (res.code === 1) {
          _this.memberData = res.data.list
          _this.memberShow.listCount = res.data.count
        } else {
          _this.$Message.error(res.msg)
        }
      })
    },
    changeMemberPage (page) {
      this.memberShow.currentPage = page
      this.getMemberList()
    },
    getParentIds (data, key) {
      var keys = []
      function loop (json) {
        for (var obj of json) {
          if (obj.children) {
            if (JSON.stringify(obj).match(key)) {
              keys.push(obj.key)
            }
            if (obj.key !== key) {
              loop(obj.children)
            } else {
              break
            }
          }
        }
      }
      loop(data)
      return keys
    },
    submit () {
      let _this = this
      let checkedNodes = _this.$refs['formTree'].getCheckedNodes()
      let tmpKeys = []
      checkedNodes.map(item => {
        let parents = _this.getParentIds(_this.ruleList, item.key)
        tmpKeys = tmpKeys.concat(parents)
      })
      checkedNodes.map(item => {
        tmpKeys.push(item.key)
      })
      // 去重
      let tmp = new Set(tmpKeys)
      _this.formItem.rules = Array.from(tmp)
      _this.$refs['myForm'].validate((valid) => {
        if (valid) {
          _this.modalSetting.loading = true
          if (_this.formItem.id === 0) {
            addGroup(_this.formItem).then(res => {
              if (res.code === 1) {
                _this.$Message.success(res.msg)
                _this.getList()
              } else {
                _this.$Message.error(res.msg)
              }
              _this.cancel()
            })
          } else {
            editGroup(_this.formItem.id, _this.formItem).then(res => {
              if (res.code === 1) {
                _this.$Message.success(res.msg)
                _this.getList()
              } else {
                _this.$Message.error(res.msg)
              }
              _this.cancel()
            })
          }
        }
      })
    },
    cancel () {
      this.modalSetting.show = false
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0
        this.$refs['myForm'].resetFields()
        this.modalSetting.loading = false
        this.modalSetting.index = 0
      }
    },
    alertAdd () {
      getRules().then(res => {
        if (res.code === 1) {
          this.ruleList = res.data
        } else {
          this.$Message.error(res.msg)
        }
      })
      this.modalSetting.show = true
    }
  },
  mounted () {
    this.getList()
  }
}
</script>

<style>
.ivu-card-head p{
  height: 32px;
  line-height: 32px;
}
.rule-list {
  height: 300px;
  border: 1px solid #dddee1;
  border-radius: 5px;
  padding: 10px;
  overflow: auto;
}
</style>
